<template>
  <div class="sub-category">
    <!-- 二级分类 -->
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />

      <!-- 筛选区域 -->
      <sub-filter @filter-change="changeFilter"></sub-filter>

      <!-- 结果区域 -->
      <div class="goods-list">
      <!-- 排序组件 -->
        <sub-sort @sort-change="changeSort"></sub-sort>
        <!-- 列表结果 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id">
            <goods-item :goods="item"></goods-item>
          </li>
        </ul>

        <XtxInfiniteLoading :loading="loading" :finished="finished" @infinite="getData" />r5
      </div>

    </div>
  </div>
</template>

<script>
import SubBread from '@/views/category/components/sub-bread'
import SubFilter from '@/views/category/components/sub-filter'
import SubSort from '@/views/category/components/sub-sort'
import GoodsItem from '@/views/category/components/goods-item'
import { ref, watch } from 'vue'
import { findSubCategoryGoods } from '@/api/category.js'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },

  setup () {
    const route = useRoute()

    const loading = ref(false)
    const finished = ref(false)

    const goodsList = ref([])

    let reqParams = {
      page: 1,
      pageSize: 20
    }

    const getData = () => {
      loading.value = true

      findSubCategoryGoods(reqParams).then(({ result }) => {
        if (result.items.length) {
          goodsList.value.push(...result.items)
          reqParams.page++
        } else {
          finished.value = true
        }

        loading.value = false
      })
    }

    const changeFilter = (filterParams) => {
      reqParams = { ...reqParams, ...filterParams }
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
    }

    const changeSort = (filterParams) => {
      reqParams = { ...reqParams, ...filterParams }
      reqParams.page = 1
      goodsList.value = []
      finished.value = false
    }

    // 切换其他二级路由时，路由组件不会被销毁，watch侦听，重新获取数据
    watch(() => route.params.id, (newVal) => {
      if (newVal && route.path === ('/category/sub/' + newVal)) {
        goodsList.value = []
        reqParams = {
          page: 1,
          pageSize: 20
        }
        finished.value = false
      }
    })

    return { loading, finished, goodsList, getData, changeFilter, changeSort }
  }

}
</script>

<style lang="less" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;

   ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
